#include "StdAfx.h"
#include "GameMain.h"

CGameMain::CGameMain(void)
{
	keyBuffer = 0;
	currentStateID = STATE_LOGO;

	timer = 20;	
	isPlaying = true;

	// Push all States here
	pGameStates.push_back((CGameState*)new CGameStateLogo(this));
	pGameStates.push_back((CGameState*)new CGameStateLose(this));
	pGameStates.push_back((CGameState*)new CGameStateWin(this));
	pGameStates.push_back((CGameState*)new CGameStateLv1(this));
	pGameStates.push_back((CGameState*)new CGameStateLv2(this));
	pGameStates.push_back((CGameState*)new CGameStateLv3(this));
	pGameStates.push_back((CGameState*)new CGameStateLv4(this));
	pGameStates.push_back((CGameState*)new CGameStateLv5(this));

	exitCurrentState = false;
	enterNextState = true;
}

CGameMain::~CGameMain(void)
{
}

void CGameMain::GameLoop() {

	while (isPlaying) {
		if (enterNextState) {
			SendMessage(MESSAGE_ENTER);
			enterNextState = false;
		}

		SendMessage(MESSAGE_UPDATE);
		SendMessage(MESSAGE_PAINT);
		
		if (exitCurrentState) {
			SendMessage(MESSAGE_EXIT);
			enterNextState = true;
			exitCurrentState = false;
		}

		::Sleep(timer);
	}

}

void CGameMain::SwitchState(int stateID) {

	SendMessage(MESSAGE_EXIT);
	currentStateID		= stateID;
	exitCurrentState	= true;
	keyBuffer			= 0;

}
void CGameMain::SendMessage(int msg) {

	CGameState* _gs = GetGameState(currentStateID);
	if (_gs) {
		_gs->StateHandler(msg, pDC, keyBuffer);
	}

}
CGameState* CGameMain::GetGameState(int iGameState) {

	for (int i=0; i < pGameStates.size(); i++) {
		CGameState* _gs = pGameStates[i];
		if ( _gs->GameStateID == iGameState )
			return pGameStates[i];
	}
	return NULL;

} 


void CGameMain::KeyPressed(int iKey) {
	keyBuffer |= iKey;
}
void CGameMain::KeyReleased(int iKey) {
	keyBuffer &= ~iKey;
}
void CGameMain::SetHDC(HDC* hDC) {
	pDC = hDC;
}